<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>zookeeper源码分析-选举算法 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第二十五篇博客–zookeeper源码分析-选举算法 入口类启动zookeeper后输入java命令jps，查看到线程运行的主类为QuoRumPeerMainQuoRumPeerMain的启动方法根据启动命令传递的参数，读取配置文件去解析，根据是单机还是集群使用不同的方法运行12345678910111213141516171819202122232425protected v">
<meta property="og:type" content="article">
<meta property="og:title" content="zookeeper源码分析-选举算法">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/07/28/zookeeper源码分析-选举算法/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第二十五篇博客–zookeeper源码分析-选举算法 入口类启动zookeeper后输入java命令jps，查看到线程运行的主类为QuoRumPeerMainQuoRumPeerMain的启动方法根据启动命令传递的参数，读取配置文件去解析，根据是单机还是集群使用不同的方法运行12345678910111213141516171819202122232425protected v">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://eetal.gitee.io/blog/images/zookeeper/jps查看主类.jpg">
<meta property="og:updated_time" content="2019-07-31T18:17:26.548Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="zookeeper源码分析-选举算法">
<meta name="twitter:description" content="欢迎查看Eetal的第二十五篇博客–zookeeper源码分析-选举算法 入口类启动zookeeper后输入java命令jps，查看到线程运行的主类为QuoRumPeerMainQuoRumPeerMain的启动方法根据启动命令传递的参数，读取配置文件去解析，根据是单机还是集群使用不同的方法运行12345678910111213141516171819202122232425protected v">
<meta name="twitter:image" content="http://eetal.gitee.io/blog/images/zookeeper/jps查看主类.jpg">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-zookeeper源码分析-选举算法" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/07/28/zookeeper源码分析-选举算法/" class="article-date">
  	<time datetime="2019-07-28T15:20:50.486Z" itemprop="datePublished">2019-07-28</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      zookeeper源码分析-选举算法
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第二十五篇博客–zookeeper源码分析-选举算法</p>
<h2 id="入口类"><a href="#入口类" class="headerlink" title="入口类"></a>入口类</h2><p>启动zookeeper后输入java命令jps，查看到线程运行的主类为QuoRumPeerMain<br><img src="/blog/images/zookeeper/jps查看主类.jpg" alt="QuoRumPeerMain"><br>QuoRumPeerMain的启动方法根据启动命令传递的参数，读取配置文件去解析，根据是单机还是集群使用不同的方法运行<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">protected void initializeAndRun(String[] args)</span><br><span class="line">       throws ConfigException, IOException, AdminServerException</span><br><span class="line">   &#123;</span><br><span class="line">       QuorumPeerConfig config = new QuorumPeerConfig();</span><br><span class="line">       <span class="keyword">if</span> (args.length == 1) &#123;</span><br><span class="line">           config.parse(args[0]);</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       // Start and schedule the the purge task</span><br><span class="line">       DatadirCleanupManager purgeMgr = new DatadirCleanupManager(config</span><br><span class="line">               .getDataDir(), config.getDataLogDir(), config</span><br><span class="line">               .getSnapRetainCount(), config.getPurgeInterval());</span><br><span class="line">       purgeMgr.start();</span><br><span class="line">	</span><br><span class="line">	//如果是集群模式，使用runFromConfig方法，否则使用ZooKeeperServerMain.main方法运行</span><br><span class="line">       <span class="keyword">if</span> (args.length == 1 &amp;&amp; config.isDistributed()) &#123;</span><br><span class="line">           runFromConfig(config);</span><br><span class="line">       &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">           LOG.warn(<span class="string">"Either no config or no quorum defined in config, running "</span></span><br><span class="line">                   + <span class="string">" in standalone mode"</span>);</span><br><span class="line">           // there is only server <span class="keyword">in</span> the quorum -- run as standalone</span><br><span class="line">           ZooKeeperServerMain.main(args);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="集群运行"><a href="#集群运行" class="headerlink" title="集群运行"></a>集群运行</h2><p>runFromConfig方法根据传递进来的配置信息，绑定成员quorumPeer，加载属性<br>quorumPeer.setQuorumVerifier(config.getQuorumVerifier(), false)这一句代码加载的QuorumVerifier包含了从配置文件解析来的集群中所有成员的信息对象<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">public void runFromConfig(QuorumPeerConfig config)</span><br><span class="line">           throws IOException, AdminServerException</span><br><span class="line">   &#123;</span><br><span class="line">	......</span><br><span class="line"></span><br><span class="line">         quorumPeer = getQuorumPeer();</span><br><span class="line">         quorumPeer.setTxnFactory(new FileTxnSnapLog(</span><br><span class="line">                     config.getDataLogDir(),</span><br><span class="line">                     config.getDataDir()));</span><br><span class="line">         quorumPeer.enableLocalSessions(config.areLocalSessionsEnabled());</span><br><span class="line">         quorumPeer.enableLocalSessionsUpgrading(</span><br><span class="line">             config.isLocalSessionsUpgradingEnabled());</span><br><span class="line">         //quorumPeer.setQuorumPeers(config.getAllMembers());</span><br><span class="line">         quorumPeer.setElectionType(config.getElectionAlg());</span><br><span class="line">         quorumPeer.setMyid(config.getServerId());</span><br><span class="line">         quorumPeer.setTickTime(config.getTickTime());</span><br><span class="line">         quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout());</span><br><span class="line">         quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout());</span><br><span class="line">         quorumPeer.setInitLimit(config.getInitLimit());</span><br><span class="line">         quorumPeer.setSyncLimit(config.getSyncLimit());</span><br><span class="line">         quorumPeer.setConfigFileName(config.getConfigFilename());</span><br><span class="line">         quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory()));</span><br><span class="line">         quorumPeer.setQuorumVerifier(config.getQuorumVerifier(), <span class="literal">false</span>);</span><br><span class="line">         <span class="keyword">if</span> (config.getLastSeenQuorumVerifier()!=null) &#123;</span><br><span class="line">             quorumPeer.setLastSeenQuorumVerifier(config.getLastSeenQuorumVerifier(), <span class="literal">false</span>);</span><br><span class="line">         &#125;</span><br><span class="line">         quorumPeer.initConfigInZKDatabase();</span><br><span class="line">         quorumPeer.setCnxnFactory(cnxnFactory);</span><br><span class="line">         quorumPeer.setSecureCnxnFactory(secureCnxnFactory);</span><br><span class="line">         quorumPeer.setSslQuorum(config.isSslQuorum());</span><br><span class="line">         quorumPeer.setUsePortUnification(config.shouldUsePortUnification());</span><br><span class="line">         quorumPeer.setLearnerType(config.getPeerType());</span><br><span class="line">         quorumPeer.setSyncEnabled(config.getSyncEnabled());</span><br><span class="line">         quorumPeer.setQuorumListenOnAllIPs(config.getQuorumListenOnAllIPs());</span><br><span class="line">         <span class="keyword">if</span> (config.sslQuorumReloadCertFiles) &#123;</span><br><span class="line">             quorumPeer.getX509Util().enableCertFileReloading();</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         // sets quorum sasl authentication configurations</span><br><span class="line">         quorumPeer.setQuorumSaslEnabled(config.quorumEnableSasl);</span><br><span class="line">         <span class="keyword">if</span>(quorumPeer.isQuorumSaslAuthEnabled())&#123;</span><br><span class="line">             quorumPeer.setQuorumServerSaslRequired(config.quorumServerRequireSasl);</span><br><span class="line">             quorumPeer.setQuorumLearnerSaslRequired(config.quorumLearnerRequireSasl);</span><br><span class="line">             quorumPeer.setQuorumServicePrincipal(config.quorumServicePrincipal);</span><br><span class="line">             quorumPeer.setQuorumServerLoginContext(config.quorumServerLoginContext);</span><br><span class="line">             quorumPeer.setQuorumLearnerLoginContext(config.quorumLearnerLoginContext);</span><br><span class="line">         &#125;</span><br><span class="line">         quorumPeer.setQuorumCnxnThreadsSize(config.quorumCnxnThreadsSize);</span><br><span class="line">         quorumPeer.initialize();</span><br><span class="line">         </span><br><span class="line">         quorumPeer.start();</span><br><span class="line">         quorumPeer.join();</span><br><span class="line">	......</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">	public interface QuorumVerifier &#123;</span><br><span class="line">    long getWeight(long id);</span><br><span class="line">    boolean containsQuorum(Set&lt;Long&gt; <span class="built_in">set</span>);</span><br><span class="line">    long getVersion();</span><br><span class="line">    void setVersion(long ver);</span><br><span class="line">    Map&lt;Long, QuorumServer&gt; getAllMembers();//全部集群成员</span><br><span class="line">    Map&lt;Long, QuorumServer&gt; getVotingMembers();//参与投票成员</span><br><span class="line">    Map&lt;Long, QuorumServer&gt; getObservingMembers();//观察者成员</span><br><span class="line">    boolean equals(Object o);</span><br><span class="line">    String toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接下来调用start方法开始运行QuorumPeer线程成员<br>start方法被重写了，在开始运行前做了一些处理<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">  @Override</span><br><span class="line">  public synchronized void <span class="function"><span class="title">start</span></span>() &#123;</span><br><span class="line">      <span class="keyword">if</span> (!getView().containsKey(myid)) &#123;</span><br><span class="line">	//getView是根据前面配置信息解析设置的QuorumVerifier，获取全部集群机器的id和ip端口信息</span><br><span class="line">	//此处判断当前机器是否在集群里</span><br><span class="line">          throw new RuntimeException(<span class="string">"My id "</span> + myid + <span class="string">" not in the peer list"</span>);</span><br><span class="line">       &#125;</span><br><span class="line">      loadDataBase();//从数据日志文件恢复数据到内存</span><br><span class="line">......</span><br><span class="line">      startLeaderElection();//开启选举</span><br><span class="line">      super.start();//线程类的start方法，开始运行run</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<p>选举运行，此时刚进入集群节点状态为LOOKING，第一票投票给自己<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public class QuorumPeerConfig &#123;</span><br><span class="line">    protected int electionAlg = 3;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">synchronized public void <span class="function"><span class="title">startLeaderElection</span></span>() &#123;</span><br><span class="line">......</span><br><span class="line">   <span class="keyword">if</span> (getPeerState() == ServerState.LOOKING) &#123;</span><br><span class="line">		//投票给自己</span><br><span class="line">	   currentVote = new Vote(myid, getLastLoggedZxid(), getCurrentEpoch());</span><br><span class="line">   &#125;</span><br><span class="line">......</span><br><span class="line">this.electionAlg = createElectionAlgorithm(electionType);//挑选选举算法---配置文件不设置默认为3</span><br><span class="line">&#125;</span><br><span class="line"> protected Election createElectionAlgorithm(int electionAlgorithm)&#123;</span><br><span class="line">       Election le=null;</span><br><span class="line"></span><br><span class="line">       //TODO: use a factory rather than a switch</span><br><span class="line">       switch (electionAlgorithm) &#123;</span><br><span class="line">       <span class="keyword">case</span> 0:</span><br><span class="line">           le = new LeaderElection(this);</span><br><span class="line">           <span class="built_in">break</span>;</span><br><span class="line">       <span class="keyword">case</span> 1:</span><br><span class="line">           le = new AuthFastLeaderElection(this);</span><br><span class="line">           <span class="built_in">break</span>;</span><br><span class="line">       <span class="keyword">case</span> 2:</span><br><span class="line">           le = new AuthFastLeaderElection(this, <span class="literal">true</span>);</span><br><span class="line">           <span class="built_in">break</span>;</span><br><span class="line">       <span class="keyword">case</span> 3:</span><br><span class="line">           QuorumCnxManager qcm = createCnxnManager();</span><br><span class="line">           QuorumCnxManager oldQcm = qcmRef.getAndSet(qcm);</span><br><span class="line">           <span class="keyword">if</span> (oldQcm != null) &#123;</span><br><span class="line">               LOG.warn(<span class="string">"Clobbering already-set QuorumCnxManager (restarting leader election?)"</span>);</span><br><span class="line">               oldQcm.halt();</span><br><span class="line">           &#125;</span><br><span class="line">           QuorumCnxManager.Listener listener = qcm.listener;</span><br><span class="line">           <span class="keyword">if</span>(listener != null)&#123;</span><br><span class="line">               listener.start();</span><br><span class="line">               FastLeaderElection fle = new FastLeaderElection(this, qcm);</span><br><span class="line">               fle.start();</span><br><span class="line">               le = fle;</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">               LOG.error(<span class="string">"Null listener when initializing cnx manager"</span>);</span><br><span class="line">           &#125;</span><br><span class="line">           <span class="built_in">break</span>;</span><br><span class="line">       default:</span><br><span class="line">           assert <span class="literal">false</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="built_in">return</span> le;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>zookeeper依赖jmx去实现集群操作，会将自身的运行线程quorumPeer封装为一个QuorumBean，通过MBeanRegistry注册到jmx上<br>MBeanRegistry是zookeeper封装了对MBeanServer的一些操作的一个类，主要完成对objectName的自动生成<br>MBeanRegistry注册时要指定parent，根据parent会自动生成objectName<br>rmi与MBean相关的源码分析请参照本人的另外两篇博客：<br>    1.<a href="https://blog.csdn.net/weixin_44627989/article/details/93055791" target="_blank" rel="noopener">java-rmi源码解析</a><br>    2.<a href="https://blog.csdn.net/weixin_44627989/article/details/95337583" target="_blank" rel="noopener">MBean与JMX</a><br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line">public class MBeanRegistry &#123;</span><br><span class="line">    private static final Logger LOG = LoggerFactory.getLogger(MBeanRegistry.class);</span><br><span class="line">    </span><br><span class="line">    private static volatile MBeanRegistry instance = new MBeanRegistry();</span><br><span class="line">    </span><br><span class="line">    private final Object LOCK = new Object();</span><br><span class="line">    </span><br><span class="line">    private Map&lt;ZKMBeanInfo, String&gt; mapBean2Path =</span><br><span class="line">        new ConcurrentHashMap&lt;ZKMBeanInfo, String&gt;();</span><br><span class="line">    </span><br><span class="line">    private MBeanServer mBeanServer;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Useful <span class="keyword">for</span> unit tests. Change the MBeanRegistry instance</span><br><span class="line">     *</span><br><span class="line">     * @param instance new instance</span><br><span class="line">     */</span><br><span class="line">    public static void setInstance(MBeanRegistry instance) &#123;</span><br><span class="line">        MBeanRegistry.instance = instance;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static MBeanRegistry <span class="function"><span class="title">getInstance</span></span>() &#123;</span><br><span class="line">        <span class="built_in">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="title">MBeanRegistry</span></span> () &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            mBeanServer = ManagementFactory.getPlatformMBeanServer();        </span><br><span class="line">        &#125; catch (Error e) &#123;</span><br><span class="line">            // Account <span class="keyword">for</span> running within IKVM and create a new MBeanServer</span><br><span class="line">            // <span class="keyword">if</span> the PlatformMBeanServer does not exist.</span><br><span class="line">            mBeanServer =  MBeanServerFactory.createMBeanServer();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Return the underlying MBeanServer that is being</span><br><span class="line">     * used to register MBean<span class="string">'s. The returned MBeanServer</span></span><br><span class="line"><span class="string">     * may be a new empty MBeanServer if running through IKVM.</span></span><br><span class="line"><span class="string">     */</span></span><br><span class="line"><span class="string">    public MBeanServer getPlatformMBeanServer() &#123;</span></span><br><span class="line"><span class="string">        return mBeanServer;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    /**</span></span><br><span class="line"><span class="string">     * Registers a new MBean with the platform MBean server. </span></span><br><span class="line"><span class="string">     * @param bean the bean being registered</span></span><br><span class="line"><span class="string">     * @param parent if not null, the new bean will be registered as a child</span></span><br><span class="line"><span class="string">     * node of this parent.</span></span><br><span class="line"><span class="string">     */</span></span><br><span class="line"><span class="string">    public void register(ZKMBeanInfo bean, ZKMBeanInfo parent)</span></span><br><span class="line"><span class="string">        throws JMException</span></span><br><span class="line"><span class="string">    &#123;</span></span><br><span class="line"><span class="string">        assert bean != null;</span></span><br><span class="line"><span class="string">        String path = null;</span></span><br><span class="line"><span class="string">        if (parent != null) &#123;</span></span><br><span class="line"><span class="string">            path = mapBean2Path.get(parent);</span></span><br><span class="line"><span class="string">            assert path != null;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">        path = makeFullPath(path, parent);</span></span><br><span class="line"><span class="string">        if(bean.isHidden())</span></span><br><span class="line"><span class="string">            return;</span></span><br><span class="line"><span class="string">        ObjectName oname = makeObjectName(path, bean);</span></span><br><span class="line"><span class="string">        try &#123;</span></span><br><span class="line"><span class="string">            synchronized (LOCK) &#123;</span></span><br><span class="line"><span class="string">                mBeanServer.registerMBean(bean, oname);</span></span><br><span class="line"><span class="string">                mapBean2Path.put(bean, path);</span></span><br><span class="line"><span class="string">            &#125;</span></span><br><span class="line"><span class="string">        &#125; catch (JMException e) &#123;</span></span><br><span class="line"><span class="string">            LOG.warn("Failed to register MBean " + bean.getName());</span></span><br><span class="line"><span class="string">            throw e;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br></pre></td></tr></table></figure></p>
<p>run方法细节，将本地的jmxQuorumBean注册到jmx，并且根据读取配置文件的集群信息，把每个远程节点的信息封装以后，以本机节点jmxQuorumBean为parent，注册到Jmx上<br>接下来因为状态为欸LOOKING，进入选举方法<br>setCurrentVote(makeLEStrategy().lookForLeader());<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">    public void <span class="function"><span class="title">run</span></span>() &#123;</span><br><span class="line">        updateThreadName();</span><br><span class="line"></span><br><span class="line">            jmxQuorumBean = new QuorumBean(this);</span><br><span class="line">            MBeanRegistry.getInstance().register(jmxQuorumBean, null);</span><br><span class="line">            <span class="keyword">for</span>(QuorumServer s: getView().values())&#123;</span><br><span class="line">                ZKMBeanInfo p;</span><br><span class="line">                <span class="keyword">if</span> (getId() == s.id) &#123;</span><br><span class="line">                    p = jmxLocalPeerBean = new LocalPeerBean(this);</span><br><span class="line">                    try &#123;</span><br><span class="line">                        MBeanRegistry.getInstance().register(p, jmxQuorumBean);</span><br><span class="line">                    &#125; catch (Exception e) &#123;</span><br><span class="line">                        LOG.warn(<span class="string">"Failed to register with JMX"</span>, e);</span><br><span class="line">                        jmxLocalPeerBean = null;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    RemotePeerBean rBean = new RemotePeerBean(this, s);</span><br><span class="line">                    try &#123;</span><br><span class="line">                        MBeanRegistry.getInstance().register(rBean, jmxQuorumBean);</span><br><span class="line">                        jmxRemotePeerBean.put(s.id, rBean);</span><br><span class="line">                    &#125; catch (Exception e) &#123;</span><br><span class="line">                        LOG.warn(<span class="string">"Failed to register with JMX"</span>, e);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            /*</span><br><span class="line">             * Main loop</span><br><span class="line">             */</span><br><span class="line">            <span class="keyword">while</span> (running) &#123;</span><br><span class="line">                switch (getPeerState()) &#123;</span><br><span class="line">                <span class="keyword">case</span> LOOKING:</span><br><span class="line">                    LOG.info(<span class="string">"LOOKING"</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> (Boolean.getBoolean(<span class="string">"readonlymode.enabled"</span>)) &#123;</span><br><span class="line">                        LOG.info(<span class="string">"Attempting to start ReadOnlyZooKeeperServer"</span>);</span><br><span class="line"></span><br><span class="line">                        // Create <span class="built_in">read</span>-only server but don<span class="string">'t start it immediately</span></span><br><span class="line"><span class="string">                        final ReadOnlyZooKeeperServer roZk =</span></span><br><span class="line"><span class="string">                            new ReadOnlyZooKeeperServer(logFactory, this, this.zkDb);</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">                        // Instead of starting roZk immediately, wait some grace</span></span><br><span class="line"><span class="string">                        // period before we decide we'</span>re partitioned.</span><br><span class="line">                        //</span><br><span class="line">                        // Thread is used here because otherwise it would require</span><br><span class="line">                        // changes <span class="keyword">in</span> each of election strategy classes <span class="built_in">which</span> is</span><br><span class="line">                        // unnecessary code coupling.</span><br><span class="line">                        Thread roZkMgr = new <span class="function"><span class="title">Thread</span></span>() &#123;</span><br><span class="line">                            public void <span class="function"><span class="title">run</span></span>() &#123;</span><br><span class="line">                                try &#123;</span><br><span class="line">                                    // lower-bound grace period to 2 secs</span><br><span class="line">                                    sleep(Math.max(2000, tickTime));</span><br><span class="line">                                    <span class="keyword">if</span> (ServerState.LOOKING.equals(getPeerState())) &#123;</span><br><span class="line">                                        roZk.startup();</span><br><span class="line">                                    &#125;</span><br><span class="line">                                &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                                    LOG.info(<span class="string">"Interrupted while attempting to start ReadOnlyZooKeeperServer, not started"</span>);</span><br><span class="line">                                &#125; catch (Exception e) &#123;</span><br><span class="line">                                    LOG.error(<span class="string">"FAILED to start ReadOnlyZooKeeperServer"</span>, e);</span><br><span class="line">                                &#125;</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;;</span><br><span class="line">                        try &#123;</span><br><span class="line">                            roZkMgr.start();</span><br><span class="line">                            reconfigFlagClear();</span><br><span class="line">                            <span class="keyword">if</span> (shuttingDownLE) &#123;</span><br><span class="line">                                shuttingDownLE = <span class="literal">false</span>;</span><br><span class="line">                                startLeaderElection();</span><br><span class="line">                            &#125;</span><br><span class="line">                            setCurrentVote(makeLEStrategy().lookForLeader());</span><br><span class="line">                        &#125; catch (Exception e) &#123;</span><br><span class="line">                            LOG.warn(<span class="string">"Unexpected exception"</span>, e);</span><br><span class="line">                            setPeerState(ServerState.LOOKING);</span><br><span class="line">                        &#125; finally &#123;</span><br><span class="line">                            // If the thread is <span class="keyword">in</span> the the grace period, interrupt</span><br><span class="line">                            // to come out of waiting.</span><br><span class="line">                            roZkMgr.interrupt();</span><br><span class="line">                            roZk.shutdown();</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        try &#123;</span><br><span class="line">                           reconfigFlagClear();</span><br><span class="line">                            <span class="keyword">if</span> (shuttingDownLE) &#123;</span><br><span class="line">                               shuttingDownLE = <span class="literal">false</span>;</span><br><span class="line">                               startLeaderElection();</span><br><span class="line">                               &#125;</span><br><span class="line">                            setCurrentVote(makeLEStrategy().lookForLeader());</span><br><span class="line">                        &#125; catch (Exception e) &#123;</span><br><span class="line">                            LOG.warn(<span class="string">"Unexpected exception"</span>, e);</span><br><span class="line">                            setPeerState(ServerState.LOOKING);</span><br><span class="line">                        &#125;                        </span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="built_in">break</span>;</span><br><span class="line">			.....</span><br><span class="line">            &#125;</span><br><span class="line">		......</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>根据前面分析得知，使用的默认选举策略为FastLeaderElection<br>FastLeaderElection构造时会实例化一个Messager<br>Messenger实例化时会创建两个线程，一个负责接收消息，一个负责发送消息启动两个线程，一个负责接收消息，一个负责发送消息<br>而FastLeaderElection对象前面挑选选举算法时，构建完成就会调用start方法，对应会启动两个工作线程开始接收和发送消息<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">   public FastLeaderElection(QuorumPeer self, QuorumCnxManager manager)&#123;</span><br><span class="line">       this.stop = <span class="literal">false</span>;</span><br><span class="line">       this.manager = manager;</span><br><span class="line">       starter(self, manager);</span><br><span class="line">   &#125;</span><br><span class="line">   LinkedBlockingQueue&lt;ToSend&gt; sendqueue;</span><br><span class="line">   LinkedBlockingQueue&lt;Notification&gt; recvqueue;</span><br><span class="line">   /**</span><br><span class="line">    * This method is invoked by the constructor. Because it is a</span><br><span class="line">    * part of the starting procedure of the object that must be on</span><br><span class="line">    * any constructor of this class, it is probably best to keep as</span><br><span class="line">    * a separate method. As we have a single constructor currently,</span><br><span class="line">    * it is not strictly necessary to have it separate.</span><br><span class="line">    *</span><br><span class="line">    * @param self      QuorumPeer that created this object</span><br><span class="line">    * @param manager   Connection manager</span><br><span class="line">    */</span><br><span class="line">   private void starter(QuorumPeer self, QuorumCnxManager manager) &#123;</span><br><span class="line">       this.self = self;</span><br><span class="line">       proposedLeader = -1;</span><br><span class="line">       proposedZxid = -1;</span><br><span class="line"></span><br><span class="line">       sendqueue = new LinkedBlockingQueue&lt;ToSend&gt;();</span><br><span class="line">       recvqueue = new LinkedBlockingQueue&lt;Notification&gt;();</span><br><span class="line">       this.messenger = new Messenger(manager);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">Messenger(QuorumCnxManager manager) &#123;</span><br><span class="line"></span><br><span class="line">	this.ws = new WorkerSender(manager);</span><br><span class="line"></span><br><span class="line">	this.wsThread = new Thread(this.ws,</span><br><span class="line">			<span class="string">"WorkerSender[myid="</span> + self.getId() + <span class="string">"]"</span>);</span><br><span class="line">	this.wsThread.setDaemon(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">	this.wr = new WorkerReceiver(manager);</span><br><span class="line"></span><br><span class="line">	this.wrThread = new Thread(this.wr,</span><br><span class="line">			<span class="string">"WorkerReceiver[myid="</span> + self.getId() + <span class="string">"]"</span>);</span><br><span class="line">	this.wrThread.setDaemon(<span class="literal">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * Starts instances of WorkerSender and WorkerReceiver</span><br><span class="line"> */</span><br><span class="line">void <span class="function"><span class="title">start</span></span>()&#123;</span><br><span class="line">	this.wsThread.start();</span><br><span class="line">	this.wrThread.start();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该策略为搜寻收到的消息，如果收到的消息的epoch大于当前epoch（朝代），更新本地保存的朝代，直接清空所有的接受消息，对比消息投票属性和自己的初始化属性，如果对方胜出，则将投票改为选举对方挑选的leader，否则投票给自己（初始化时的id-myid）<br>以下为对比方法（epoch都是peerEpoch)<br>((newEpoch &gt; curEpoch) ||<br>                ((newEpoch == curEpoch) &amp;&amp;<br>                ((newZxid &gt; curZxid) || ((newZxid == curZxid) &amp;&amp; (newId &gt; curId)))))<br>胜出条件:<br>    1.朝代大于当前朝代<br>    2.朝代相等，并且zxid大的 或者 （zxid相等并且id更大的）———-因为zxid代表事务id，更大相当于对方处理了更多的leader消息<br>当没有新的投票消息时，则继续发送自己的投票消息（sendNotification方法实际只是将消息加入阻塞队列，真正进行发送处理的是另一个WorkerSender线程子类实例，该线程循环获取阻塞队列的消息，进行发送，对应的接受消息是WorkerReader线程子类实例）<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line">public Vote lookForLeader() throws InterruptedException &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            self.jmxLeaderElectionBean = new LeaderElectionBean();</span><br><span class="line">            MBeanRegistry.getInstance().register(</span><br><span class="line">                    self.jmxLeaderElectionBean, self.jmxLocalPeerBean);</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            LOG.warn(<span class="string">"Failed to register with JMX"</span>, e);</span><br><span class="line">            self.jmxLeaderElectionBean = null;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (self.start_fle == 0) &#123;</span><br><span class="line">           self.start_fle = Time.currentElapsedTime();</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;</span><br><span class="line">            HashMap&lt;Long, Vote&gt; recvset = new HashMap&lt;Long, Vote&gt;();</span><br><span class="line"></span><br><span class="line">            HashMap&lt;Long, Vote&gt; outofelection = new HashMap&lt;Long, Vote&gt;();</span><br><span class="line"></span><br><span class="line">            int notTimeout = finalizeWait;</span><br><span class="line"></span><br><span class="line">            synchronized(this)&#123;</span><br><span class="line">                logicalclock.incrementAndGet();</span><br><span class="line">                updateProposal(getInitId(), getInitLastLoggedZxid(), getPeerEpoch());</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            LOG.info(<span class="string">"New election. My id =  "</span> + self.getId() +</span><br><span class="line">                    <span class="string">", proposed zxid=0x"</span> + Long.toHexString(proposedZxid));</span><br><span class="line">            sendNotifications();</span><br><span class="line"></span><br><span class="line">            /*</span><br><span class="line">             * Loop <span class="keyword">in</span> <span class="built_in">which</span> we exchange notifications until we find a leader</span><br><span class="line">             */</span><br><span class="line"></span><br><span class="line">            <span class="keyword">while</span> ((self.getPeerState() == ServerState.LOOKING) &amp;&amp;</span><br><span class="line">                    (!stop))&#123;</span><br><span class="line">                /*</span><br><span class="line">                 * Remove next notification from queue, <span class="built_in">times</span> out after 2 <span class="built_in">times</span></span><br><span class="line">                 * the termination time</span><br><span class="line">                 */</span><br><span class="line">                Notification n = recvqueue.poll(notTimeout,</span><br><span class="line">                        TimeUnit.MILLISECONDS);</span><br><span class="line"></span><br><span class="line">                /*</span><br><span class="line">                 * Sends more notifications <span class="keyword">if</span> haven<span class="string">'t received enough.</span></span><br><span class="line"><span class="string">                 * Otherwise processes new notification.</span></span><br><span class="line"><span class="string">                 */</span></span><br><span class="line"><span class="string">                if(n == null)&#123;</span></span><br><span class="line"><span class="string">                    if(manager.haveDelivered())&#123;</span></span><br><span class="line"><span class="string">						//如果全部发送完了，再次发送一次投票信息</span></span><br><span class="line"><span class="string">                        sendNotifications();</span></span><br><span class="line"><span class="string">                    &#125; else &#123;</span></span><br><span class="line"><span class="string">						//没发送完，可能出现故障，重新连接每一台集群中的机器</span></span><br><span class="line"><span class="string">                        manager.connectAll();</span></span><br><span class="line"><span class="string">                    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                    /*</span></span><br><span class="line"><span class="string">                     * Exponential backoff</span></span><br><span class="line"><span class="string">                     */</span></span><br><span class="line"><span class="string">                    int tmpTimeOut = notTimeout*2;</span></span><br><span class="line"><span class="string">                    notTimeout = (tmpTimeOut &lt; maxNotificationInterval?</span></span><br><span class="line"><span class="string">                            tmpTimeOut : maxNotificationInterval);</span></span><br><span class="line"><span class="string">                    LOG.info("Notification time out: " + notTimeout);</span></span><br><span class="line"><span class="string">                &#125; </span></span><br><span class="line"><span class="string">                else if (validVoter(n.sid) &amp;&amp; validVoter(n.leader)) &#123;</span></span><br><span class="line"><span class="string">                    /*</span></span><br><span class="line"><span class="string">                     * Only proceed if the vote comes from a replica in the current or next</span></span><br><span class="line"><span class="string">                     * voting view for a replica in the current or next voting view.</span></span><br><span class="line"><span class="string">                     */</span></span><br><span class="line"><span class="string">                    switch (n.state) &#123;</span></span><br><span class="line"><span class="string">                    case LOOKING:</span></span><br><span class="line"><span class="string">                        // If notification &gt; current, replace and send messages out</span></span><br><span class="line"><span class="string">                        if (n.electionEpoch &gt; logicalclock.get()) &#123;</span></span><br><span class="line"><span class="string">                            logicalclock.set(n.electionEpoch);</span></span><br><span class="line"><span class="string">                            recvset.clear();</span></span><br><span class="line"><span class="string">                            if(totalOrderPredicate(n.leader, n.zxid, n.peerEpoch,</span></span><br><span class="line"><span class="string">                                    getInitId(), getInitLastLoggedZxid(), getPeerEpoch())) &#123;</span></span><br><span class="line"><span class="string">                                updateProposal(n.leader, n.zxid, n.peerEpoch);</span></span><br><span class="line"><span class="string">                            &#125; else &#123;</span></span><br><span class="line"><span class="string">                                updateProposal(getInitId(),</span></span><br><span class="line"><span class="string">                                        getInitLastLoggedZxid(),</span></span><br><span class="line"><span class="string">                                        getPeerEpoch());</span></span><br><span class="line"><span class="string">                            &#125;</span></span><br><span class="line"><span class="string">                            sendNotifications();</span></span><br><span class="line"><span class="string">                        &#125; else if (n.electionEpoch &lt; logicalclock.get()) &#123;</span></span><br><span class="line"><span class="string">                            if(LOG.isDebugEnabled())&#123;</span></span><br><span class="line"><span class="string">                                LOG.debug("Notification election epoch is smaller than logicalclock. n.electionEpoch = 0x"</span></span><br><span class="line"><span class="string">                                        + Long.toHexString(n.electionEpoch)</span></span><br><span class="line"><span class="string">                                        + ", logicalclock=0x" + Long.toHexString(logicalclock.get()));</span></span><br><span class="line"><span class="string">                            &#125;</span></span><br><span class="line"><span class="string">                            break;</span></span><br><span class="line"><span class="string">                        &#125; else if (totalOrderPredicate(n.leader, n.zxid, n.peerEpoch,</span></span><br><span class="line"><span class="string">                                proposedLeader, proposedZxid, proposedEpoch)) &#123;</span></span><br><span class="line"><span class="string">                            updateProposal(n.leader, n.zxid, n.peerEpoch);</span></span><br><span class="line"><span class="string">                            sendNotifications();</span></span><br><span class="line"><span class="string">                        &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                        if(LOG.isDebugEnabled())&#123;</span></span><br><span class="line"><span class="string">                            LOG.debug("Adding vote: from=" + n.sid +</span></span><br><span class="line"><span class="string">                                    ", proposed leader=" + n.leader +</span></span><br><span class="line"><span class="string">                                    ", proposed zxid=0x" + Long.toHexString(n.zxid) +</span></span><br><span class="line"><span class="string">                                    ", proposed election epoch=0x" + Long.toHexString(n.electionEpoch));</span></span><br><span class="line"><span class="string">                        &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                        // don'</span>t care about the version <span class="keyword">if</span> it<span class="string">'s in LOOKING state</span></span><br><span class="line"><span class="string">                        recvset.put(n.sid, new Vote(n.leader, n.zxid, n.electionEpoch, n.peerEpoch));</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                        if (termPredicate(recvset,</span></span><br><span class="line"><span class="string">                                new Vote(proposedLeader, proposedZxid,</span></span><br><span class="line"><span class="string">                                        logicalclock.get(), proposedEpoch))) &#123;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                            // Verify if there is any change in the proposed leader</span></span><br><span class="line"><span class="string">                            while((n = recvqueue.poll(finalizeWait,</span></span><br><span class="line"><span class="string">                                    TimeUnit.MILLISECONDS)) != null)&#123;</span></span><br><span class="line"><span class="string">                                if(totalOrderPredicate(n.leader, n.zxid, n.peerEpoch,</span></span><br><span class="line"><span class="string">                                        proposedLeader, proposedZxid, proposedEpoch))&#123;</span></span><br><span class="line"><span class="string">                                    recvqueue.put(n);</span></span><br><span class="line"><span class="string">                                    break;</span></span><br><span class="line"><span class="string">                                &#125;</span></span><br><span class="line"><span class="string">                            &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">                            /*</span></span><br><span class="line"><span class="string">                             * This predicate is true once we don'</span>t <span class="built_in">read</span> any new</span><br><span class="line">                             * relevant message from the reception queue</span><br><span class="line">                             */</span><br><span class="line">                            <span class="keyword">if</span> (n == null) &#123;</span><br><span class="line">                                self.setPeerState((proposedLeader == self.getId()) ?</span><br><span class="line">                                        ServerState.LEADING: learningState());</span><br><span class="line">                                Vote endVote = new Vote(proposedLeader,</span><br><span class="line">                                        proposedZxid, logicalclock.get(), </span><br><span class="line">                                        proposedEpoch);</span><br><span class="line">                                leaveInstance(endVote);</span><br><span class="line">                                <span class="built_in">return</span> endVote;</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="built_in">break</span>;</span><br><span class="line">						......</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">if</span> (!validVoter(n.leader)) &#123;</span><br><span class="line">                        LOG.warn(<span class="string">"Ignoring notification for non-cluster member sid &#123;&#125; from sid &#123;&#125;"</span>, n.leader, n.sid);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (!validVoter(n.sid)) &#123;</span><br><span class="line">                        LOG.warn(<span class="string">"Ignoring notification for sid &#123;&#125; from non-quorum member sid &#123;&#125;"</span>, n.leader, n.sid);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">return</span> null;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                <span class="keyword">if</span>(self.jmxLeaderElectionBean != null)&#123;</span><br><span class="line">                    MBeanRegistry.getInstance().unregister(</span><br><span class="line">                            self.jmxLeaderElectionBean);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; catch (Exception e) &#123;</span><br><span class="line">                LOG.warn(<span class="string">"Failed to unregister with JMX"</span>, e);</span><br><span class="line">            &#125;</span><br><span class="line">            self.jmxLeaderElectionBean = null;</span><br><span class="line">            LOG.debug(<span class="string">"Number of connection processing threads: &#123;&#125;"</span>,</span><br><span class="line">                    manager.getConnectionThreadCount());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>投票以后会进入选举是否完成的判断,如果确定选举有了结果就会设置自身的状态并结束选举<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (termPredicate(recvset,</span><br><span class="line">		new Vote(proposedLeader, proposedZxid,</span><br><span class="line">				logicalclock.get(), proposedEpoch))) &#123;</span><br><span class="line"></span><br><span class="line">	// Verify <span class="keyword">if</span> there is any change <span class="keyword">in</span> the proposed leader</span><br><span class="line">	<span class="keyword">while</span>((n = recvqueue.poll(finalizeWait,</span><br><span class="line">			TimeUnit.MILLISECONDS)) != null)&#123;</span><br><span class="line">		<span class="keyword">if</span>(totalOrderPredicate(n.leader, n.zxid, n.peerEpoch,</span><br><span class="line">				proposedLeader, proposedZxid, proposedEpoch))&#123;</span><br><span class="line">			recvqueue.put(n);</span><br><span class="line">			<span class="built_in">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/*</span><br><span class="line">	 * This predicate is <span class="literal">true</span> once we don<span class="string">'t read any new</span></span><br><span class="line"><span class="string">	 * relevant message from the reception queue</span></span><br><span class="line"><span class="string">	 */</span></span><br><span class="line"><span class="string">	if (n == null) &#123;</span></span><br><span class="line"><span class="string">		self.setPeerState((proposedLeader == self.getId()) ?</span></span><br><span class="line"><span class="string">				ServerState.LEADING: learningState());</span></span><br><span class="line"><span class="string">		Vote endVote = new Vote(proposedLeader,</span></span><br><span class="line"><span class="string">				proposedZxid, logicalclock.get(), </span></span><br><span class="line"><span class="string">				proposedEpoch);</span></span><br><span class="line"><span class="string">		leaveInstance(endVote);</span></span><br><span class="line"><span class="string">		return endVote;</span></span><br><span class="line"><span class="string">	&#125;</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">protected boolean termPredicate(Map&lt;Long, Vote&gt; votes, Vote vote) &#123;</span></span><br><span class="line"><span class="string">       SyncedLearnerTracker voteSet = new SyncedLearnerTracker();</span></span><br><span class="line"><span class="string">       voteSet.addQuorumVerifier(self.getQuorumVerifier());</span></span><br><span class="line"><span class="string">       if (self.getLastSeenQuorumVerifier() != null</span></span><br><span class="line"><span class="string">               &amp;&amp; self.getLastSeenQuorumVerifier().getVersion() &gt; self</span></span><br><span class="line"><span class="string">                       .getQuorumVerifier().getVersion()) &#123;</span></span><br><span class="line"><span class="string">           voteSet.addQuorumVerifier(self.getLastSeenQuorumVerifier());</span></span><br><span class="line"><span class="string">       &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">       /*</span></span><br><span class="line"><span class="string">        * First make the views consistent. Sometimes peers will have different</span></span><br><span class="line"><span class="string">        * zxids for a server depending on timing.</span></span><br><span class="line"><span class="string">        */</span></span><br><span class="line"><span class="string">       for (Map.Entry&lt;Long, Vote&gt; entry : votes.entrySet()) &#123;</span></span><br><span class="line"><span class="string">           if (vote.equals(entry.getValue())) &#123;</span></span><br><span class="line"><span class="string">               voteSet.addAck(entry.getKey());</span></span><br><span class="line"><span class="string">           &#125;</span></span><br><span class="line"><span class="string">       &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">       return voteSet.hasAllQuorums();</span></span><br><span class="line"><span class="string">   &#125;</span></span><br></pre></td></tr></table></figure></p>
<p>SyncedLearnerTracker中投票结果的判定是这样实现的<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public boolean <span class="function"><span class="title">hasAllQuorums</span></span>() &#123;</span><br><span class="line">    <span class="keyword">for</span> (QuorumVerifierAcksetPair qvAckset : qvAcksetPairs) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!qvAckset.getQuorumVerifier().containsQuorum(qvAckset.getAckset()))</span><br><span class="line">            <span class="built_in">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>而 在QuorumPeerConfig加载配置文件解析时就实例化，根据使用带权重的还是不带权重，分别使用QuorumHierarchical和QuorumMaj<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line">   void setupQuorumPeerConfig(Properties prop, boolean configBackwardCompatibilityMode)</span><br><span class="line">           throws IOException, ConfigException &#123;</span><br><span class="line">       quorumVerifier = parseDynamicConfig(prop, electionAlg, <span class="literal">true</span>, configBackwardCompatibilityMode);</span><br><span class="line">       setupMyId();</span><br><span class="line">       setupClientPort();</span><br><span class="line">       setupPeerType();</span><br><span class="line">       checkValidity();</span><br><span class="line">   &#125;</span><br><span class="line">public static QuorumVerifier parseDynamicConfig(Properties dynamicConfigProp, int eAlg, boolean warnings,</span><br><span class="line">   boolean configBackwardCompatibilityMode) throws IOException, ConfigException &#123;</span><br><span class="line">      boolean isHierarchical = <span class="literal">false</span>;</span><br><span class="line">       <span class="keyword">for</span> (Entry&lt;Object, Object&gt; entry : dynamicConfigProp.entrySet()) &#123;</span><br><span class="line">           String key = entry.getKey().toString().trim();                    </span><br><span class="line">           <span class="keyword">if</span> (key.startsWith(<span class="string">"group"</span>) || key.startsWith(<span class="string">"weight"</span>)) &#123;</span><br><span class="line">              isHierarchical = <span class="literal">true</span>;</span><br><span class="line">           &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!configBackwardCompatibilityMode &amp;&amp; !key.startsWith(<span class="string">"server."</span>) &amp;&amp; !key.equals(<span class="string">"version"</span>))&#123; </span><br><span class="line">              LOG.info(dynamicConfigProp.toString());</span><br><span class="line">              throw new ConfigException(<span class="string">"Unrecognised parameter: "</span> + key);                </span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       </span><br><span class="line">       QuorumVerifier qv = createQuorumVerifier(dynamicConfigProp, isHierarchical);</span><br><span class="line">              </span><br><span class="line">       int numParticipators = qv.getVotingMembers().size();</span><br><span class="line">       int numObservers = qv.getObservingMembers().size();</span><br><span class="line">       <span class="keyword">if</span> (numParticipators == 0) &#123;</span><br><span class="line">           <span class="keyword">if</span> (!standaloneEnabled) &#123;</span><br><span class="line">               throw new IllegalArgumentException(<span class="string">"standaloneEnabled = false then "</span> +</span><br><span class="line">                       <span class="string">"number of participants should be &gt;0"</span>);</span><br><span class="line">           &#125;</span><br><span class="line">           <span class="keyword">if</span> (numObservers &gt; 0) &#123;</span><br><span class="line">               throw new IllegalArgumentException(<span class="string">"Observers w/o participants is an invalid configuration"</span>);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">else</span> <span class="keyword">if</span> (numParticipators == 1 &amp;&amp; standaloneEnabled) &#123;</span><br><span class="line">           // HBase currently adds a single server line to the config, <span class="keyword">for</span></span><br><span class="line">           // b/w compatibility reasons we need to keep this here. If standaloneEnabled</span><br><span class="line">           // is <span class="literal">true</span>, the QuorumPeerMain script will create a standalone server instead</span><br><span class="line">           // of a quorum configuration</span><br><span class="line">           LOG.error(<span class="string">"Invalid configuration, only one server specified (ignoring)"</span>);</span><br><span class="line">           <span class="keyword">if</span> (numObservers &gt; 0) &#123;</span><br><span class="line">               throw new IllegalArgumentException(<span class="string">"Observers w/o quorum is an invalid configuration"</span>);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">           <span class="keyword">if</span> (warnings) &#123;</span><br><span class="line">               <span class="keyword">if</span> (numParticipators &lt;= 2) &#123;</span><br><span class="line">                   LOG.warn(<span class="string">"No server failure will be tolerated. "</span> +</span><br><span class="line">                       <span class="string">"You need at least 3 servers."</span>);</span><br><span class="line">               &#125; <span class="keyword">else</span> <span class="keyword">if</span> (numParticipators % 2 == 0) &#123;</span><br><span class="line">                   LOG.warn(<span class="string">"Non-optimial configuration, consider an odd number of servers."</span>);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">           /*</span><br><span class="line">            * If using FLE, <span class="keyword">then</span> every server requires a separate election</span><br><span class="line">            * port.</span><br><span class="line">            */            </span><br><span class="line">          <span class="keyword">if</span> (eAlg != 0) &#123;</span><br><span class="line">              <span class="keyword">for</span> (QuorumServer s : qv.getVotingMembers().values()) &#123;</span><br><span class="line">                  <span class="keyword">if</span> (s.electionAddr == null)</span><br><span class="line">                      throw new IllegalArgumentException(</span><br><span class="line">                              <span class="string">"Missing election port for server: "</span> + s.id);</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;   </span><br><span class="line">       &#125;</span><br><span class="line">       <span class="built_in">return</span> qv;</span><br><span class="line">   &#125;</span><br><span class="line">private static QuorumVerifier createQuorumVerifier(Properties dynamicConfigProp, boolean isHierarchical) throws ConfigException&#123;</span><br><span class="line">      <span class="keyword">if</span>(isHierarchical)&#123;</span><br><span class="line">           <span class="built_in">return</span> new QuorumHierarchical(dynamicConfigProp);</span><br><span class="line">       &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          /*</span><br><span class="line">            * The default QuorumVerifier is QuorumMaj</span><br><span class="line">            */        </span><br><span class="line">           //LOG.info(<span class="string">"Defaulting to majority quorums"</span>);</span><br><span class="line">           <span class="built_in">return</span> new QuorumMaj(dynamicConfigProp);            </span><br><span class="line">       &#125;          </span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>简单分析QuorumMaj，其判断作为leader的条件就是得票数超过一半<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public QuorumMaj(Properties props) throws ConfigException &#123;</span><br><span class="line">    <span class="keyword">for</span> (Entry&lt;Object, Object&gt; entry : props.entrySet()) &#123;</span><br><span class="line">        String key = entry.getKey().toString();</span><br><span class="line">        String value = entry.getValue().toString();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (key.startsWith(<span class="string">"server."</span>)) &#123;</span><br><span class="line">            int dot = key.indexOf(<span class="string">'.'</span>);</span><br><span class="line">            long sid = Long.parseLong(key.substring(dot + 1));</span><br><span class="line">            QuorumServer qs = new QuorumServer(sid, value);</span><br><span class="line">            allMembers.put(Long.valueOf(sid), qs);</span><br><span class="line">            <span class="keyword">if</span> (qs.type == LearnerType.PARTICIPANT)</span><br><span class="line">                votingMembers.put(Long.valueOf(sid), qs);</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                observingMembers.put(Long.valueOf(sid), qs);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.equals(<span class="string">"version"</span>)) &#123;</span><br><span class="line">            version = Long.parseLong(value, 16);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    half = votingMembers.size() / 2;</span><br><span class="line">&#125;</span><br><span class="line">public boolean containsQuorum(Set&lt;Long&gt; ackSet) &#123;</span><br><span class="line">    <span class="built_in">return</span> (ackSet.size() &gt; half);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="更多精彩内容"><a href="#更多精彩内容" class="headerlink" title="更多精彩内容"></a>更多精彩内容</h3><h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/07/31/zookeeper源码分析-事件注册及通信原理/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          zookeeper源码分析-事件注册及通信原理
        
      </div>
    </a>
  
  
    <a href="/blog/2019/07/19/zookeeper协调原理/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">zookeeper协调原理</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="zookeeper源码分析-选举算法" data-title="zookeeper源码分析-选举算法" data-url="http://eetal.gitee.io/blog/blog/2019/07/28/zookeeper源码分析-选举算法/"  data-images="/blog/images/head.jpg" data-content="zookeeper源码分析-选举算法">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>